package com.wondertek.mist.photo;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

public class UpIoadFileUtil
{
	private String mUrl;
	private File mFile;
	private OnUploadProcessListener mOnUploadProcessListener;
	private Map<String, String> mParam;

	public UpIoadFileUtil(String url, File file, OnUploadProcessListener onUploadProcessListener, Map<String, String> param)
	{
		mUrl = url;
		mFile = file;
		mOnUploadProcessListener = onUploadProcessListener;
		mParam = param;
	}

	public void StartUpIoadFile()
	{
		new Thread(new Runnable()
		{

			@Override
			public void run()
			{
				try
				{
					mOnUploadProcessListener.initUpload();
					uploadSubmit(mUrl, mParam, mFile);

				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}

		}).start();

	}

	private String uploadSubmit(String url, Map<String, String> param, File file) throws Exception
	{
		HttpPost post = new HttpPost(url);
		HttpClient httpClient = new DefaultHttpClient();
		MultipartEntity entity = new MultipartEntity();
		if (param != null && !param.isEmpty())
		{
			for (Map.Entry<String, String> entry : param.entrySet())
			{
				entity.addPart(entry.getKey(), new StringBody(entry.getValue()));
			}
		}
		// 添加文件参数
		if (file != null && file.exists())
		{
			entity.addPart("file", new FileBody(file));
		}
		post.setEntity(entity);
		HttpResponse response = httpClient.execute(post);
		int stateCode = response.getStatusLine().getStatusCode();
		StringBuffer sb = new StringBuffer();
		if (stateCode == HttpStatus.SC_OK)
		{
			HttpEntity result = response.getEntity();
			if (result != null)
			{
				InputStream is = result.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				String tempLine;
				while ((tempLine = br.readLine()) != null)
				{
					sb.append(tempLine);
				}
			}
			else
			{
				System.out.println("result == null");
			}
		}
		else
		{
			System.out.println("stateCode != HttpStatus.SC_OK");
		}
		post.abort();
		mOnUploadProcessListener.onUploadDone(sb.toString());
		return sb.toString();
	}
}
